package com.project.server;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 封装读取流的请求对象
 */
public class Request {
    /**
     * 客户端请求服务器路径
     */
    private String url;
    /**
     * 客户端请求表单数据
     */
    private Map<String, String> paramMap = new HashMap<>();

    public Request(InputStream in) {
        try {
            byte[] bytesArray = new byte[1024];
            //将读取流中的数据，读取到指定数组
            in.read(bytesArray);
            //将字节数组的数据转化为字符串
            String str = new String(bytesArray).trim();
            System.out.println(str);
            //分析请求
            this.analysis(str);

            //把字符串按一个或多个空格拆分
//            String[] array = str.split("\\s+");
//            this.url = array[1].substring(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void analysis(String str) {
        String[] array = str.split("\\s+");
        if (array[0].equals("GET")) {
            if (!array[1].contains("?")) {
                this.url = array[1].substring(1);
            }else {
                int index = array[1].indexOf('?');
                this.url=array[1].substring(1,index);
                String value = array[1].substring(index+1);
                String[]valueArr = value.split("&");
                for (String KV:valueArr) {
                    String[] tmp = KV.split("=");
                    if(tmp.length==2){
                        this.paramMap.put(tmp[0],tmp[1]);
                    }else {
                        this.paramMap.put(tmp[0],"");
                    }

                }
            }
        }else if (array[0].equals("POST")){
            this.url = array[1].substring(1);
            String value = array[array.length-1];
            String[]valueArr = value.split("&");
            for (String KV:valueArr) {
                String[] tmp = KV.split("=");
                if (tmp.length==2){
                    this.paramMap.put(tmp[0],tmp[1]);
                }else {
                    this.paramMap.put(tmp[0],"");
                }

            }
        }
    }


    public String getUrl() {
        return url;
    }

    @Override
    public String toString() {
        return "Request{" +
                "url='" + url + '\'' +
                ", paramMap=" + paramMap +
                '}';
    }
}
